# -*- coding: utf-8 -*-
"""
Created on Tue Nov 28 12:34:12 2017

@author: Luther
"""

import requests
from bs4 import BeautifulSoup
import pandas as pd
from tqdm import tqdm

input_path = input("请输入输入文件路径：")
#input_path = "C:\Users\Luther\Desktop\Belt_Road\data\py\add_py_input.xls"

add = pd.read_excel(input_path)
#add.index = add.id
#add = add.drop('id', axis=1)

lng = []
lat = []
count = 0
for i in tqdm(range(len(add))):

    address = add.iloc[i].values[0]
    url = "http://api.map.baidu.com/geocoder/v2/?address={:}&output=xml&ak=5mSNiWKjGK0FZtuL5yc09GRb4wHYDiNU&callback=showLocation".format(
        address)
    try:
        r = requests.get(url, timeout=120)
        r.raise_for_status
        soup = BeautifulSoup(r.text, 'lxml')
        if int(soup.status.string) == 0:
            lng.append(float(soup.lng.string))
            lat.append(float(soup.lat.string))
        else:
            lng.append(0)
            lat.append(0)
    except:
        lng.append(0)
        lat.append(0)

    count = count + 1
    #print("\r当前进度: {:.2f}%".format(count * 100 / len(add)), end="")

add['lng'] = lng
add['lat'] = lat
output_path = input("请输入输出文件路径：")
#output_path = "C:\Users\Luther\Desktop\Belt_Road\data\py\add_py_output.xls"
add.to_excel(output_path)
